<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :before-open="beforeOpen"
      :search.sync="search"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.badRecordQuery_register" @click="handleRegister">登记</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button type="primary" size="small" v-if="permission.badRecordQuery_stationDataShow" @click="handleStationDataShow">数据展示在工站</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoCommonModal('searchWorkOrderNoModal')"></el-button>
        </el-input>
      </template>
      <!-- <template slot-scope="" slot="partNoSearch">
        <el-input placeholder="请选择 产品编码" readonly="true" v-model="search.partNo">
          <el-button slot="append" icon="el-icon-search" @click="openPartNoCommonModal(searchPartNoModal)"></el-button>
        </el-input>
      </template> -->
      <template slot="mainCauseNameSearch">
        <el-select v-model="search.mainCauseName" placeholder="请选择不良原因大类" :clearable="true">
          <el-option v-for="item in mainCauseList" :key="item.value" :label="item.name" :value="JSON.stringify(item)"> </el-option>
        </el-select>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.badRecordQuery_delete" :disabled="!row.registerType" @click="$refs.crud.rowDel(row)"
          >删除</el-button
        >
      </template>
    </avue-crud>
    <el-dialog class="dialog" ref="dialog" title="登记" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" @close="closeDialog">
      <avue-form v-if="showDialog" ref="registerForm" v-model="registerInfo" :option="dialogOption"></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="registerSubmit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <el-dialog class="dialog" ref="dialog" title="数据展示在工站" append-to-body :visible.sync="showToStationDialog" :close-on-click-modal="false">
      <avue-crud :option="stationDataOption" :table-loading="stationDataLoading" :data="stationData" v-model="form" ref="stationCrud" @row-del="rowStationDel"></avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showToStationDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button size="small" type="primary" :disabled="stationData.length == 0" @click="noShowDataToStation"><span>批量不展示</span></el-button>
        <el-button size="small" type="primary" :disabled="stationData.length == 0" @click="showDataToStation"><span>批量展示</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/mro/centerproduct/failure/page"
      :option="option"
      :page="page"
      :exclude="['lineName', 'fromRouteName']"
      :query="exportParams"
      file-name="不良记录"
    >
    </export-comp>
  </basic-container>
</template>

<script>
import { getList, isShowDataToStation, registerFailure, getWorkOrderDetail, remove, getFeddingPartModelList } from '@/api/report/bad-record-query';
import { mapGetters } from 'vuex';
import { getList as getFailureConfigList, getDetail as getFailureConfigDetail } from '@/api/repair/failureconfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getToken } from '@/util/auth';
import exportComp from '@/components/export-comp';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config/index.vue';
import { filterEmptyValues } from '@/util/util';

export default {
  name: 'ReportBadRecordQuery',
  components: {
    CommonModalTemplate,
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'BAD_RECORD_QUERY',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      defaults: {},
      exportParams: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      showToStationDialog: false,
      // stationPage: {
      //   pageSize: 20,
      //   currentPage: 1,
      //   total: 0
      // },
      stationData: [],
      stationDataOption: {
        // height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        labelWidth: 100,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: false,
        delBtn: true,
        addBtn: false,
        refreshBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        menu: true,
        menuWidth: 100,
        column: [
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '数据展示工站页面',
            prop: 'isShowOnStation',
            type: 'switch',
            row: true,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            span: 24
          }
        ]
      },
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        labelWidth: 100,
        border: true,
        index: true,
        editBtn: false,
        viewBtn: false,
        selection: true,
        delBtn: false,
        addBtn: false,
        dialogClickModal: false,
        indexLabel: '序号',
        searchMenuPosition: 'right',
        columnBtn: false,
        menu: true,
        menuWidth: 100,
        searchLabelWidth: 100,
        column: [
          {
            label: '条码类型',
            prop: 'objectType',
            search: true,
            type: 'select',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ],
            searchOrder: 2
          },
          {
            label: '序列号',
            prop: 'productSequenceNumber',
            search: true,
            searchOrder: 3
          },
          {
            label: '外部序列号',
            prop: 'outSequenceNumber',
            search: true,
            searchOrder: 10
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 1
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '不良登记人',
            prop: 'registryByName'
          },
          {
            label: '不良登记时间',
            prop: 'registryDate'
          },
          {
            label: '产线名称',
            prop: 'lineName',
            type: 'select',
            searchOrder: 8,
            search: true,
            dicUrl: '/api/mes-product/productionline/list',
            props: {
              label: 'name',
              value: 'name'
            }
          },
          {
            label: '不良工序',
            prop: 'fromRouteName',
            search: true,
            searchOrder: 4,
            type: 'select',
            dicUrl: '/api/mes-product/apaasworkstation/workstation/list',
            props: {
              label: 'name',
              value: 'code'
            }
          },
          {
            label: '不良现象代码',
            prop: 'failureCode'
          },
          {
            label: '不良现象描述',
            prop: 'failureName'
          },
          {
            label: '不良确认人',
            prop: 'createUserName'
          },
          {
            label: '不良确认时间',
            prop: 'createTime',
            width: 130,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          },
          {
            label: '不良确认时间',
            prop: 'createTimes',
            type: 'datetimerange',
            width: 130,
            search: true,
            searchOrder: 9,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            hide: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          },
          // {
          //   label: '不良解除人',
          //   width: 90,
          //   prop: 'relieveByName'
          // },
          // {
          //   label: '不良解除时间',
          //   width: 90,
          //   prop: 'relieveTime'
          // },
          {
            label: '不良原因大类',
            prop: 'mainCauseName',
            search: true,
            searchOrder: 5
          },
          {
            label: '不良原因小类',
            prop: 'subCauseName',
            search: true,
            searchOrder: 6,
            type: 'select',
            dicData: []
          },
          {
            label: '不良确认结果',
            prop: 'handlingResult',
            search: true,
            searchOrder: 7,
            type: 'select',
            dicData: [
              {
                label: '产品维修',
                value: 'REPAIR'
              },
              {
                label: '产品报废',
                value: 'SCRAP'
              },
              {
                label: '解除不良',
                value: 'RELIEVE'
              }
            ],
            html: true,
            formatter: (val) => {
              if (val.handlingResult == 'REPAIR') {
                return `<span style="color: #86aed3;cursor: pointer;" onclick="goMaintenance('${val.objectType}', '${val.productSequenceNumber}','REPAIR')">产品维修</span>`;
              }
              if (val.handlingResult === 'SCRAP') {
                return `<span style="color: #86aed3;cursor: pointer;" onclick="goMaintenance('${val.objectType}', '${val.productSequenceNumber}','SCRAP')">产品报废</span>`;
              }
              if (val.handlingResult === 'RELIEVE') {
                return '解除不良';
              }
            }
          },
          {
            label: '登记类型',
            prop: 'registerType',
            type: 'select',
            value: '3',
            dicData: [
              { label: '客退', value: '1' },
              { label: '投诉', value: '2' },
              { label: '重要事项', value: '3' }
            ]
          },
          {
            label: '不良数量',
            prop: 'quantity'
          },
          {
            label: '物料型号',
            prop: 'ngPartModel'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      data: [],
      mainCauseList: [],
      showDialog: false,
      registerInfo: {},
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '150',
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openWorkOrderNoCommonModal('registerWorkOrderModal');
            }
          },
          {
            label: '产品编码',
            prop: 'partNo',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择产品编码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartNoCommonModal('registerPartNoModal');
            }
          },
          {
            label: '产品名称',
            prop: 'partName',
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            disabled: true
          },
          {
            label: '登记类型',
            prop: 'registerType',
            type: 'select',
            value: '3',
            dicData: [
              { label: '客退', value: 1 },
              { label: '投诉', value: 2 },
              { label: '重要事项', value: '3' }
            ],
            control: (val, form) => {
              let remark = this.findObject(this.dialogOption.column, 'remark');
              if (val) {
                remark.rules[0].required = false;
              } else {
                remark.rules[0].required = true;
              }
            }
            // rules: [
            //   {
            //     required: true,
            //     message: '请选择登记类型',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            label: '不良代码',
            prop: 'failureCode',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: false,
                message: '请选择不良代码',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openFailureCodeCommonModal();
            }
          },
          {
            label: '不良现象',
            prop: 'failureName',
            disabled: true,
            rules: [
              {
                required: false,
                message: '请选择不良现象',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良数量',
            prop: 'quantity',
            type: 'number',
            precision: 0,
            minRows: 0,
            rules: [
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value === 0) {
                    callback(new Error('不良数量不能等于0'));
                  } else if (!value) {
                    callback(new Error('不良数量不能为空'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '数据展示工站页面',
            prop: 'isShowOnStation',
            type: 'switch',
            row: true,
            value: false,
            labelTip: '启动后，数据会展示在模切工站，印刷工站，不良报工工站的产品品质履历图中，每款产品最多展示10个！',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            span: 24,
            rules: [
              {
                required: false,
                message: '请输入备注',
                trigger: 'blur'
              }
            ]
          }
          // {
          //   label: '物料型号',
          //   prop: 'ngPartModel',
          //   type: 'select',
          //   dicData: []
          // }
        ]
      },
      ngPartList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  watch: {
    'search.mainCauseName'(val) {
      this.search.subCauseName = '';
      const column = this.findObject(this.option.column, 'subCauseName');
      column.dicData = [];
      if (val) {
        getFailureConfigDetail(JSON.parse(val).id)
          .then((res) => {
            column.dicData = this._get(res, 'data.data.subList', []);
            column.dicData = this._map(column.dicData, (item) => {
              return {
                label: item.name,
                value: item.code
              };
            });
          })
          .catch((err) => {
            column.dicData = [];
          });
      }
    }
  },
  created() {
    let startDate = this.$moment(new Date()).format('YYYY-MM-DD');
    let endDate = this.$moment(new Date()).format('YYYY-MM-DD');
    startDate = startDate + ' ' + '00:00:00';
    endDate = endDate + ' ' + '23:59:59';
    this.$set(this.search, 'createTimes', [startDate, endDate]);
    this.query.createTimes = this.search.createTimes;
    window.goMaintenance = this.goMaintenance;
    let urlQuery = this.$route.query;
    if (urlQuery && urlQuery.sequenceNumber && urlQuery.objectType && urlQuery.confirmTime) {
      this.search.productSequenceNumber = decodeURIComponent(urlQuery.sequenceNumber);
      this.search.objectType = decodeURIComponent(urlQuery.objectType);
      this.query.productSequenceNumber = this.search.productSequenceNumber;
      this.query.objectType = this.search.objectType;
      let createTimes = decodeURIComponent(urlQuery.confirmTime);
      if (createTimes) {
        this.search.createTimes = [createTimes, createTimes];
        this.query.createTimes = [createTimes, createTimes];
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    getFailureConfigList(1, 10000, { dictType: 'CAUSE' })
      .then((res) => {
        this.mainCauseList = this._get(res, 'data.data.records', []);
      })
      .catch((err) => {
        this.mainCauseList = [];
      });
  },
  methods: {
    noShowDataToStation() {
      let idList = this.stationData.map((item) => item.id);
      isShowDataToStation({
        idList,
        isShowOnStation: false
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.stationData = [];
        this.showToStationDialog = false;
      });
    },
    showDataToStation() {
      let idList = this.stationData.map((item) => item.id);
      isShowDataToStation({
        idList,
        isShowOnStation: true
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.stationData = [];
        this.showToStationDialog = false;
      });
    },
    rowStationDel(row) {
      this.stationData = this._differenceWith(this.stationData, [row], (item1, item2) => {
        return item1.id === item2.id;
      });
    },
    handleStationDataShow() {
      if (this.selectionList.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择展示数据!'
        });
        return;
      }
      this.stationData = this.selectionList;
      this.showToStationDialog = true;
    },

    initData(tenantId) {},
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.createTimes && params.createTimes.length > 0) {
        params.confirmStartTime = params.createTimes[0];
        params.confirmEndTime = params.createTimes[1];
        delete params.createTimes;
      }
      if (params.fromRouteName) {
        params.fromRouteCode = params.fromRouteName;
        delete params.fromRouteName;
      }
      if (params.mainCauseName) {
        params.mainCauseCode = JSON.parse(params.mainCauseName).code;
        delete params.mainCauseName;
      }
      if (params.subCauseName) {
        params.subCauseCode = params.subCauseName;
        delete params.subCauseName;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.query.createTimes) {
        this.query.confirmStartTime = this.$moment(this.query.createTimes[0]).format('YYYY-MM-DD HH:mm:ss');
        this.query.confirmEndTime = this.$moment(this.query.createTimes[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTimes;
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        delete this.query.createTimes;
      });
    },
    // 下载
    openDownload(row) {
      if (row.fileUrl) {
        this.globalStartLoad('文件下载中，请稍后...');
        downloadFileByUrl(row.fileUrl, row.fileName);
        this.globalEndLoad();
      }
    },

    viewDetail(row) {
      this.showDialog = true;
      this.testDataDetail = row;
      this.testDataDetailResult = [];
      getDetail(row.id).then(
        (res) => {
          if (res.data && res.data.data) {
            this._forEach(res.data.data, (item) => {
              if (item.resultJson) {
                this.testDataDetailResult.push({
                  testDataDetailResult: JSON.stringify(JSON.parse(item.resultJson), null, '\t')
                });
              } else {
                this.testDataDetailResult.push({
                  testDataDetailResult: ''
                });
              }
            });
          } else {
            this.testDataDetailResult = [];
          }
        },
        (error) => {
          this.testDataDetailResult = [];
        }
      );
    },
    /**
     * 打开操作人员列表模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操作人（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    openWorkOrderNoCommonModal(name) {
      this.modalName = name;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select'
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    openPartNoCommonModal(name) {
      this.modalName = name;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=true',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '类型',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    openFailureCodeCommonModal() {
      this.modalName = 'failureCodeModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择不良代码（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_PHENOMENON',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '不良代码',
            prop: 'code',
            search: true
          },
          {
            label: '不良现象描述',
            prop: 'name'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'userModal':
          this.search.operator = this._get(rowData, 'id', '');
          this.search.operatorName = this._get(rowData, 'realName', '');
          break;
        case 'searchWorkOrderNoModal':
          this.search.workOrderId = this._get(rowData, 'id', '');
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          break;
        case 'registerWorkOrderModal':
          this.registerInfo.workOrderId = this._get(rowData, 'id', '');
          this.registerInfo.workOrderNo = this._get(rowData, 'orderNo', '');
          getWorkOrderDetail(this.registerInfo.workOrderId).then((res) => {
            this.registerInfo.partMasterId = this._get(res, 'data.data.partMasterId', '');
            this.registerInfo.partNo = this._get(res, 'data.data.partNo', '');
            this.registerInfo.partName = this._get(res, 'data.data.partName', '');
            this.registerInfo.partModel = this._get(res, 'data.data.partModel', '');
          });
          let ngPartModel = this.findObject(this.dialogOption.column, 'ngPartModel');
          getFeddingPartModelList(this.registerInfo.workOrderId).then(
            (res) => {
              this.ngPartList = this._get(res, 'data.data', []);
              ngPartModel.dicData = this._map(this.ngPartList, (item) => {
                return {
                  label: item.partModel,
                  value: item.partModel
                };
              });
            },
            (error) => {
              ngPartModel.dicData = [];
            }
          );
          break;
        case 'searchPartNoModal':
          this.search.partId = this._get(rowData, 'id', '');
          this.search.partNo = this._get(rowData, 'partNo', '');
          break;
        case 'registerPartNoModal':
          this.registerInfo.partMasterId = this._get(rowData, 'id', '');
          this.registerInfo.partNo = this._get(rowData, 'partNo', '');
          this.registerInfo.partName = this._get(rowData, 'name', '');
          this.registerInfo.partModel = this._get(rowData, 'partModel', '');
          this.registerInfo.workOrderId = '';
          this.registerInfo.workOrderNo = '';
          break;
        case 'failureCodeModal':
          this.registerInfo.failureId = this._get(rowData, 'id', '');
          this.registerInfo.failureCode = this._get(rowData, 'code', '');
          this.registerInfo.failureName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    // handleExport() {
    //   window.open(
    //     `/api/mes-product/mro/centerproduct/export-failure?${this.website.tokenHeader}=${getToken()}&objectType=${this.query.objectType || ''}&productSequenceNumber=${
    //       this.query.productSequenceNumber || ''
    //     }&workOrderNo=${this.query.workOrderNo || ''}&fromRouteCode=${this.query.fromRouteName || ''}&mainCauseCode=${this.query.mainCauseName || ''}&subCauseCode=${
    //       this.query.subCauseName || ''
    //     }&handlingResult=${this.query.handlingResult || ''}&ids=${this.ids || ''}`
    //   );
    //   this.selectionClear();
    // },
    goMaintenance(objectType, productSequenceNumber, type) {
      localStorage.setItem('maintenanceInfo', JSON.stringify({ objectType: objectType, productSequenceNumber: productSequenceNumber }));
      if (type == 'REPAIR') {
        // 产品维修 跳转至维修详情
        this.$router.push({
          path: '/report/maintenance-record-query'
          // query: {
          //   objectType: objectType,
          //   productSequenceNumber: productSequenceNumber
          // }
        });
      } else {
        this.$router.replace('/repair/failureconfirm');
      }
    },
    handleExport() {
      if (this.query.createTimes) {
        this.query.confirmStartTime = this.$moment(this.query.createTimes[0]).format('YYYY-MM-DD HH:mm:ss');
        this.query.confirmEndTime = this.$moment(this.query.createTimes[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTimes;
      }
      this.exportParams = filterEmptyValues(this.query);
      this.$refs.exportComp.visible = true;
    },
    handleRegister() {
      this.showDialog = true;
    },
    closeDialog() {
      this.$refs.registerForm.resetFields();
      this.registerInfo = {};
      let ngPartModel = this.findObject(this.dialogOption.column, 'ngPartModel');
      ngPartModel.dicData = [];
      this.showDialog = false;
    },
    registerSubmit() {
      this.$refs.registerForm.validate((valid, done) => {
        if (valid) {
          this.registerInfo['extFields'] = JSON.stringify({ registerType: this.registerInfo.registerType });
          delete this.registerInfo.registerType;
          this.registerInfo['productHandlingResultList'] = [
            {
              resultId: this.registerInfo.failureId,
              resultCode: this.registerInfo.failureCode,
              resultName: this.registerInfo.failureName
            }
          ];
          this._forEach(this.ngPartList, (item) => {
            if (this.registerInfo.ngPartModel === item.partModel) {
              this.registerInfo['ngPartNo'] = item.partNo;
            }
          });
          registerFailure(this.registerInfo).then((res) => {
            this.$message.success(res.data.msg);
            this.showDialog = false;
            this.onLoad(this.page);
          });
        }
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    }
  }
};
</script>

<style></style>
